<script setup lang="ts">
import { ref } from "vue";
import { saveDict } from "@/api/dict";
import { ElMessage } from "element-plus";
//表单数据
const dict = ref({
  code: "",
  name: "",
  pid: 0,
  sorts: 0
})

const addFrom = ref();

//定义规则
const rules = {
  code: [
    { required: true, message: "请输入编码", trigger: "blur" }
  ],
  name: [
    { required: true, message: "请输入名称", trigger: "blur" }
  ]
};

//定义属性
const props = defineProps({
  visible: {
    type: Boolean,
    default: true
  }
});
//声明事件
const emits = defineEmits(["close", "refreshData"]);

//表单中初始化
function init(){
  dict.value={
    code: "",
    name: "",
    pid: 0,
    sorts: 0
  }
}


//关闭对话框回调
function close() {
  //触发关闭时间
  emits("close")
}

//保存
async function save() {
  let valid = await addFrom.value.validate(() => {});
  if (!valid) return;

  let res = await saveDict(dict.value);
  if(res.code == 200){
    ElMessage({
      message: "保存成功",
      type: "success"
    });
    emits("refreshData");
    close();
  }
}

//暴露方法供父组件使用
defineExpose({ init });
</script>

<template>

  <el-dialog
    :model-value="visible"
    title="添加分组"
    width="500"
    :close-on-click-modal="false"
    @close="close"
  >
    <el-form ref="addFrom" :model="dict" :rules="rules">
      <el-form-item label="编码" prop="code">
        <el-input v-model="dict.code" placeholder="请输入编码"/>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="dict.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item>
        <el-button @click="save">保存</el-button>
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>


</template>

<style scoped lang="scss">

</style>
